﻿using Dapper;
using InventoryIssue.API.Read.Application.Command.Stocktaking;
using InventoryIssue.Domain;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using InventoryIssue.Infrastructrue.Interface;
using MediatR;
using MySql.Data.MySqlClient;
using Org.BouncyCastle.Asn1.X509;
using System.Collections.Generic;
using System.Text;

namespace InventoryIssue.API.Read.Application.Handler.Stocktaking
{
    public class GetStocktakingHandler : IRequestHandler<GetStocktakingCommand, APIPaging<StocktakingModel>>
    {
        private readonly DatabaseContext db;

        public GetStocktakingHandler(DatabaseContext db)
        {
            this.db = db;
        }
        public async Task<APIPaging<StocktakingModel>> Handle(GetStocktakingCommand request, CancellationToken cancellationToken)
        {
            APIPaging<StocktakingModel> result = new APIPaging<StocktakingModel>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countSql = new StringBuilder();
            sql.Append(@"SELECT
                          Id,
                          StocktakingId,
                          StocktakingType,
                          OrderNumber,
                          Note,
                          OrderCreator,
                          OrderCreatorTime,
                          State,
                          IsDel
                        FROM
                          stocktakingmodel
                        WHERE
                          IsDel = 0");
            countSql.Append(@"SELECT
                              COUNT(Id)
                            FROM
                              stocktakingmodel
                            WHERE
                              IsDel = 0");

            if (!string.IsNullOrEmpty(request.StocktakingId))
            {
                sql.Append(" and StocktakingId LIKE @StocktakingId");
                countSql.Append(" and StocktakingId LIKE @StocktakingId");
            }
            if (request.State.HasValue)
            {
                sql.Append(" and state = @state");
                countSql.Append(" and state = @state");
            }
            if (request.OrderCreatorTime.HasValue)
            {
                sql.Append(" and OrderCreatorTime >= @OrderCreatorTime");
                countSql.Append(" and OrderCreatorTime >= @OrderCreatorTime");
            }
            sql.Append(" ORDER BY OrderCreatorTime DESC LIMIT @PageSize OFFSET @offset");
            var parameters = new
            {
                StocktakingId = $"%{request.StocktakingId}%",
                request.State,
                offset = (request.PageIndex - 1) * request.PageSize,
                request.PageSize,
                request.OrderCreatorTime
            };


            var pageData = await db.DapperConnection.QueryAsync<StocktakingModel>(sql.ToString(), parameters);
            int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
            int totalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize);

            result.Message = "显示成功";
            result.Code = APIEnum.Ok;
            result.PageDatas = pageData.ToList();
            result.TotalCount = totalCount;
            result.TotalPage = totalPage;
            return result;
        }
    }
}
